class AddOrganization < Mutations::Command
  include Wisper::Publisher
  
  required do
    string :name
    string :rank
    string :category
  end

  optional do
    integer :parent_id
    array   :requre_certificate_organs
  end

  def execute
    unless organization_rank = Organization::Rank.find_by_name(rank)
      add_error(:rank, :organization_rank_not_exist, '机构等级不存在')
      return
    end

    unless organization_category = Organization::Category.find_by_name(category)
      add_error(:category, :organization_category_not_exist, '机构类型不存在')
      return
    end

    organization = Organization.new(rank: organization_rank, category: organization_category, name: name, parent_id: parent_id)
    if organization.save
      unless requre_certificate_organs.empty?
        AssignmentPositionStandard.run(organization_id: organization.id, requre_certificate_organs: requre_certificate_organs)
      end
      return organization
    else
      organization.errors.each do |key, value|
        add_error(key, key, value)
      end
    end
  end

end